﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Timers;
using System.Linq;
using System.Text;
using Logic;

namespace Logic
{
    class ActorMessageQueue
    {
        public ConcurrentQueue<Message> Messages { get; set; }
        private Timer hasMessageTimer { get; set; }

        public string Owner { get; set; }

        public States State { get; set; }
        public enum States
        {
            Running,
            Stopped,
            Error,
            Unknown
        }

        public ActorMessageQueue(string owner)
        {
            this.Messages = new ConcurrentQueue<Message>();

            //this.State = States.Stopped;
            this.Owner = owner;
            hasMessageTimer = new Timer(1000.00);
            hasMessageTimer.Elapsed += hasMessageTimer_Elapsed;
        }

        void hasMessageTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!Messages.IsEmpty)
            {
                var msg = new Message();
                Messages.TryPeek(out msg);
                OnQueueChanged("HAS", msg);
            }
        }

        public void Add(Message newMessage)
        {
            Messages.Enqueue(newMessage);
        }

        public Message Dispatch()
        {
            var msg = new Message();
            Messages.TryDequeue(out msg);
            return msg;
        }

        public void Start()
        {
            System.Diagnostics.Debug.WriteLine(string.Format("STARTED QUEUE FOR {0}", this.Owner));
            hasMessageTimer.Start();
            this.State = States.Running;
        }

        public void Stop()
        {
            System.Diagnostics.Debug.WriteLine(string.Format("STOPPED QUEUE FOR {0}", this.Owner));
            hasMessageTimer.Stop();
            this.State = States.Stopped;
        }

        public event QueueChangedEventHandler QueueChanged;
        public void OnQueueChanged(string operation, Message msg)
        {
            if (QueueChanged != null)
            {
                QueueChanged(this, new QueueChangedEventArgs(operation, msg));
            }
        }
    }

    internal delegate void QueueChangedEventHandler(object sender, QueueChangedEventArgs e);
}
